import { PrismaClient } from '@prisma/client'
import { Honor, PaginationParams, PaginatedResponse } from '../types'

const prisma = new PrismaClient()

export class HonorService {
  async getHonors(params: PaginationParams & { memberId?: number; honorType?: string } = {}) {
    const { page = 1, limit = 10, memberId, honorType } = params
    const offset = (page - 1) * limit
    
    const where: any = {}
    
    if (memberId) {
      where.memberId = memberId
    }
    
    if (honorType) {
      where.honorType = honorType
    }

    const [honors, total] = await Promise.all([
      prisma.honor.findMany({
        where,
        skip: offset,
        take: limit,
        include: {
          member: {
            select: {
              id: true,
              name: true,
              avatar: true,
            },
          },
        },
        orderBy: { dateReceived: 'desc' },
      }),
      prisma.honor.count({ where }),
    ])

    return {
      data: honors,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }

  async createHonor(honorData: Partial<Honor>) {
    return prisma.honor.create({
      data: honorData,
      include: {
        member: {
          select: {
            id: true,
            name: true,
            avatar: true,
          },
        },
      },
    })
  }

  async getHonorById(id: number) {
    return prisma.honor.findUnique({
      where: { id },
      include: {
        member: {
          select: {
            id: true,
            name: true,
            avatar: true,
          },
        },
      },
    })
  }

  async updateHonor(id: number, updateData: Partial<Honor>) {
    return prisma.honor.update({
      where: { id },
      data: updateData,
      include: {
        member: {
          select: {
            id: true,
            name: true,
            avatar: true,
          },
        },
      },
    })
  }

  async deleteHonor(id: number) {
    return prisma.honor.delete({
      where: { id },
    })
  }

  async getHonorsByMember(memberId: number, params: PaginationParams = {}) {
    const { page = 1, limit = 10 } = params
    const offset = (page - 1) * limit
    
    const [honors, total] = await Promise.all([
      prisma.honor.findMany({
        where: { memberId },
        skip: offset,
        take: limit,
        include: {
          member: {
            select: {
              id: true,
              name: true,
              avatar: true,
            },
          },
        },
        orderBy: { dateReceived: 'desc' },
      }),
      prisma.honor.count({ where: { memberId } }),
    ])

    return {
      data: honors,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }

  async getHonorStatistics() {
    const [
      totalHonors,
      honorsByType,
      recentHonors,
      topMembers,
    ] = await Promise.all([
      prisma.honor.count(),
      
      prisma.honor.groupBy({
        by: ['honorType'],
        _count: {
          honorType: true,
        },
      }),
      
      prisma.honor.findMany({
        take: 5,
        orderBy: { createdAt: 'desc' },
        include: {
          member: {
            select: {
              id: true,
              name: true,
              avatar: true,
            },
          },
        },
      }),
      
      prisma.honor.groupBy({
        by: ['memberId'],
        _count: {
          memberId: true,
        },
        orderBy: {
          _count: {
            memberId: 'desc',
          },
        },
        take: 5,
      }),
    ])

    // Get member details for top members
    const topMemberDetails = await prisma.familyMember.findMany({
      where: {
        id: {
          in: topMembers.map(m => m.memberId),
        },
      },
      select: {
        id: true,
        name: true,
        avatar: true,
      },
    })

    return {
      total: totalHonors,
      byType: honorsByType,
      recent: recentHonors,
      topMembers: topMembers.map(m => ({
        memberId: m.memberId,
        count: m._count.memberId,
        member: topMemberDetails.find(detail => detail.id === m.memberId),
      })),
    }
  }

  async getHonorsByDateRange(startDate: Date, endDate: Date) {
    return prisma.honor.findMany({
      where: {
        dateReceived: {
          gte: startDate,
          lte: endDate,
        },
      },
      include: {
        member: {
          select: {
            id: true,
            name: true,
            avatar: true,
          },
        },
      },
      orderBy: { dateReceived: 'desc' },
    })
  }

  async searchHonors(query: string, params: PaginationParams = {}) {
    const { page = 1, limit = 10 } = params
    const offset = (page - 1) * limit
    
    const [honors, total] = await Promise.all([
      prisma.honor.findMany({
        where: {
          OR: [
            { title: { contains: query } },
            { description: { contains: query } },
            { member: { name: { contains: query } } },
          ],
        },
        skip: offset,
        take: limit,
        include: {
          member: {
            select: {
              id: true,
              name: true,
              avatar: true,
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      }),
      prisma.honor.count({
        where: {
          OR: [
            { title: { contains: query } },
            { description: { contains: query } },
            { member: { name: { contains: query } } },
          ],
        },
      }),
    ])

    return {
      data: honors,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }
}